from flask import Blueprint, render_template, flash, redirect, url_for, request
from app.backend.forms import CategorysForm
from app.models import Categorys
from app import db

bp = Blueprint('backend_categorys', __name__)


@bp.route('/')
def index():
    page = request.args.get('page', 1, type=int)
    pagination = Categorys.query.order_by(Categorys.created_at.desc()).paginate(page, 20)
    model = pagination.items
    return render_template('backend/categorys/index.html', page=page, pagination=pagination, model=model)


@bp.route('/create', methods=['GET', 'POST'])
def create():
    form = CategorysForm()
    if form.validate_on_submit():
        category = Categorys(name=form.name.data, sort=form.sort.data)
        db.session.add(category)
        db.session.commit()
        flash('Post created.', 'success')
        return redirect(url_for('backend_categorys.index'))

    return render_template('backend/categorys/create.html', form=form)


@bp.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
    form = CategorysForm()
    category = Categorys.query.get_or_404(id)
    if form.validate_on_submit():
        category.name = form.name.data
        category.sort = form.sort.data
        db.session.commit()
        flash('Category updated.', 'success')
        return redirect(url_for('backend_categorys.view', id=category.id))
    form.name.data = category.name
    form.sort.data = category.sort

    return render_template('backend/categorys/update.html', form=form)


@bp.route('/view/<int:id>')
def view(id):
    model = Categorys.query.get_or_404(id)
    return render_template('backend/categorys/view.html', model=model)


@bp.route('/delete/<int:id>', methods=['POST'])
def delete(id):
    model = Categorys.query.get_or_404(id)
    db.session.delete(model)
    db.session.commit()
    flash('删除成功', 'success')
    return redirect(url_for('backend_categorys.index'))




